import React, { useEffect, useState, forwardRef, useRef } from 'react';
import { connect } from 'dva';
import { Button, Table } from 'antd';
import router from 'umi/router';
import HeadForm from './components/headForm';
import Paging from 'components/common/paging';
import deviceCaliCn from 'columns/deviceCali';
import MessageModel from 'components/common/MessageModel';
import { caliDel, caliStop, caliOpen } from 'dic/messageModel';
import KeepAlive from 'react-activation';
import moment from 'moment';

import './index.styl';

const HeadFormRef = forwardRef((props, ref) => (
  <HeadForm {...props} cRef={ref} />
));

function DeviceCali({
  dispatch,
  deviceCali: { list, total, pageCurrent, allPages, serachParams },
  location: { params = {}, pathname },
  commonAction: { catchObj }
}) {
  const searchRef = useRef()
  const { status = '', today = '', isRefresh = false } = params;
  // 添加序号
  deviceCaliCn.list[0].render = (t, r, i) => (pageCurrent-1)*10 + i + 1;
  deviceCaliCn.list[6].render = t => {
    return <span>{t}</span>
  }

  // 执行状态
  deviceCaliCn.list[deviceCaliCn.list.length - 2].render = (t, r, i) => {
    return r.statusName !== '启用' ? '——' : r.actionStatusName
  }

  // 执行时间
  deviceCaliCn.list[deviceCaliCn.list.length - 4].render = (t, r, i) =>
    `${r.startTime} 至 ${r.endTime}`;

  // 添加操作
  deviceCaliCn.list[deviceCaliCn.list.length - 1].render = t => (
    <>
      {moment(new Date(moment(new Date()).format('YYYY/MM/DD'))) <=
        moment(new Date(t.endTime.replace(/-/g, '/'))) &&
      moment(new Date(t.startTime.replace(/-/g, '/'))) <=
        moment(new Date(moment(new Date()).format('YYYY/MM/DD'))) &&
      t.status === 3 &&
      t.actionStatus === 2 &&
      t.isActionUser ? (
        <span className="td-blue" onClick={() => toDetail(t)}>
          上传报告
        </span>
      ) : null}
      {(t.status === 1) && (t.isApprovalUser) ? (
        <span className="td-blue" onClick={() => toDetail(t)}>
          审批
        </span>
      ) : null}
      {/* 编辑 */}
      {t.status !== 3 && t.actionStatus === 1? (
        <span className="td-blue" onClick={() => toEdit(t)}>
          编辑
        </span>
      ) : null}

      {/* 删除 */}
      {t.status !== 3 ? (
        <MessageModel
          data={caliDel}
          handleClick={() => {
            dispatch({
              type: 'deviceCali/delList',
              payload: { 
                id: t.id
              }
            })
            searchRef.current.resetFields();
          }}
        />
      ) : null}
      {/* 停用 */}
      {t.status === 3 ? (
        <MessageModel
          data={caliStop}
          handleClick={() => {
            dispatch({
              type: 'deviceCali/caliStopOrOpen',
              payload: { 
                id: t.id, 
                status: 4
              }
            })
            searchRef.current.resetFields();
          }}
        />
      ) : null}
      {/* 启用 */}
      {t.status === 4 ? (
        <MessageModel
          data={caliOpen}
          handleClick={() => {
            dispatch({
              type: 'deviceCali/caliStopOrOpen',
              payload: { 
                id: t.id, 
                status: 3
              }
            });
            searchRef.current.resetFields();
          }}
        />
      ) : null}
      <span className="td-blue" onClick={() => toDetail(t)}>
        查看详情
      </span>
    </>
  );
  useEffect(() => {
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          deviceCali: [true, false]
        }
      }
    })
    return function cleanUp() {
      const nowPage = JSON.parse(localStorage.getItem('panes')).find(item => item.key === pathname)
      if (nowPage === undefined) {
        dispatch({
          type: 'deviceCali/updateList',
          payload: {
            list: [],
            total: 0,
            pageCurrent: 0,
            allPages: 0,
          }
        })
        dispatch({
          type: 'deviceUpkeep/updateSerachParams',
          payload: {
            serachParams: {}
          }
        })
      }
    }
  }, [dispatch, pathname])
  const [current] = useState(pageCurrent || 1);
  const [size] = useState(10);
  useEffect(() => {
    dispatch({
      type: 'deviceCali/getDataList',
      payload: {
        current,
        size,
        ...serachParams
      }
    })
  }, [dispatch, current, size, serachParams])
  useEffect(() => {
    if (isRefresh) {
      searchRef.current.resetFields()
    }
  },[isRefresh])
  function toDetail(t) {
    router.push({
      pathname: '/deviceCali/detail',
      query: {
        id: t.id,
      },
    });
  }
  // 编辑
  function toEdit(t) {
    router.push({
      pathname: '/deviceCali/edit',
      query: {
        id: t.id,
      },
    });
  }
  return (
    <KeepAlive name='deviceLedger' when={catchObj.deviceCali}>
      <div className="deviceCali">
        <div className="deviceCali-form">
          <HeadFormRef
            getFormData={v => {
              dispatch({
                type: 'deviceCali/updateSerachParams',
                payload: {
                  serachParams: {
                    ...v,
                    current: 1
                  }
                }
              })
            }}
            status={status}
            today={today}
            ref={searchRef}
          />
        </div>
        <div className="deviceCali-table">
          <Button className="btn blue-button" type="primary" onClick={() => router.push('/deviceCali/add')}>
            新建检定计划
          </Button>
          <Table
            columns={deviceCaliCn.list}
            dataSource={list}
            pagination={false}
            className="self-table"
            bordered={true}
            rowKey={(r) => r.id}
          />
          <Paging
            total={total}
            pageSize={10}
            handlePageChange={(c) => {
              dispatch({
                type: 'deviceCali/updateSerachParams',
                payload: {
                  serachParams: {
                    ...serachParams,
                    current: c
                  }
                }
              })
            }}
            pageCount={pageCurrent}
            pages={allPages}
          ></Paging>
        </div>
      </div>
    </KeepAlive>
  );
}

export default connect(({ deviceCali, dictionaryList, commonAction }) => ({
  deviceCali,
  dictionaryList,
  commonAction,
}))(DeviceCali);
